<template>
  <div class="page-container">
    <a-card :bordered="false" size="small" style="margin-bottom: 10px">
      <a-row :gutter="16">
        <a-col class="search-row" :span="20">
          <a-form layout="inline">
            <a-form-item label="所在周期">
              <a-date-picker
                size="small"
                v-model:value="queryParams.period"
                :picker="picker"
                :allow-clear="false"
                :disabled-date="disabledDate"
                @change="handleSearch"
              />
            </a-form-item>
            <a-form-item>
              <a-button type="primary" size="small" @click="handleSearch">查询</a-button>
            </a-form-item>
          </a-form>
          <!--<template v-if="dataSource.length">-->
          <div class="status-item">
            <span class="label">发布状态：</span>
            <span class="value">
              <!--<a-switch size="small" v-model:checked="openStatus" @change="handleChangeStatus" />-->
              <a-tag :color="openStatus ? 'green' : 'red'">{{
                openStatus ? '已发布' : '未发布'
              }}</a-tag>
            </span>
          </div>
          <div class="status-item">
            <a-button
              type="primary"
              size="small"
              @click="checkTheProgressOfTheReport"
              :disabled="!dataSource.length"
              >查看填报进度</a-button
            >
          </div>
          <!--<div class="status-item">-->
          <!--  <a-button-->
          <!--    type="primary"-->
          <!--    size="small"-->
          <!--    @click="handleExport"-->
          <!--    :disabled="!dataSource.length"-->
          <!--    >汇总并导出数据</a-button-->
          <!--  >-->
          <!--</div>-->
          <!--</template>-->
        </a-col>
        <!--<a-col class="search-row right-btn-container" :span="4">-->
        <!--  <a-button type="primary" size="small" @click="handleCopyTemplate" :disabled="openStatus"-->
        <!--    >复用之前模板</a-button-->
        <!--  >-->
        <!--  <a-upload-->
        <!--    v-model:file-list="fileList"-->
        <!--    name="avatar"-->
        <!--    list-type="picture-card"-->
        <!--    class="avatar-uploader"-->
        <!--    :show-upload-list="false"-->
        <!--    :custom-request="handleUploadTemplate"-->
        <!--    :before-upload="beforeUpload"-->
        <!--    @change="handleChange"-->
        <!--    :disabled="openStatus"-->
        <!--    accept=".xlsx"-->
        <!--  >-->
        <!--    <a-button type="primary" size="small" :disabled="openStatus"-->
        <!--      >上传模板<LoadingOutlined v-if="uploading"-->
        <!--    /></a-button>-->
        <!--  </a-upload>-->
        <!--</a-col>-->
      </a-row>
    </a-card>

    <a-table
      :dataSource="dataSource"
      :columns="columns"
      :pagination="{ pageSize: 15 }"
      size="small"
    >
      <template #bodyCell="{ record, column }">
        <template v-if="column.dataIndex === 'operation'">
          <a style="margin-right: 10px" @click="handleDisposition(record)">配置</a>
          <a style="margin-right: 10px" @click="handleDownloadTemplate(record)">下载模板</a>
          <a style="margin-right: 10px" @click="handleDel(record)">删除模板</a>
        </template>
      </template>
    </a-table>

    <a-modal v-model:open="visible" :title="title" width="500px" destroy-on-close @ok="handleOk">
      <a-form
        ref="formRef"
        :model="form"
        class="point-form"
        name="pointDetail"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 18 }"
        autocomplete="off"
      >
        <template v-if="title.indexOf('配置') > -1">
          <a-form-item
            label="汇总模式"
            name="SummaryType"
            :rules="[{ required: true, message: '请选择汇总模式!' }]"
          >
            <a-select
              v-model:value="form.SummaryType"
              size="small"
              :options="[{ value: '行' }, { value: '列' }]"
            />
          </a-form-item>

          <a-form-item
            label="汇总行/列"
            name="SummaryItems"
            :rules="[{ required: true, validator: checkSummaryItems }]"
          >
            <a-input v-model:value="form.SummaryItems" size="small" />
          </a-form-item>
          <a-form-item
            label="填报说明"
            name="Description"
            :rules="[{ required: true, message: '请输入填报说明!' }]"
          >
            <a-textarea
              v-model:value="form.Description"
              placeholder=""
              :auto-size="{ minRows: 5, maxRows: 5 }"
            />
          </a-form-item>
        </template>
        <template v-else-if="title === '复用以前的模板'">
          <div class="copy-template-container">
            <div class="copy-template-header">
              <div class="check-btn">
                <a-checkbox v-model:checked="checkAllTemplate" @change="handleSelectedAll" />
              </div>
              <div class="label">所在周期：</div>
              <div class="cycle">
                <a-date-picker
                  size="small"
                  v-model:value="period"
                  :allow-clear="false"
                  :picker="picker"
                  :disabled-date="disabledDate"
                  @change="handleSearchListOfPreviousTemplates"
                />
              </div>
              <!--<div class="search-btn">-->
              <!--  <a-button type="primary" size="small">查询</a-button>-->
              <!--</div>-->
            </div>
            <div class="previous-template-list-container">
              <div class="list-item" v-for="item in listOfPreviousTemplates" :key="item.id">
                <div class="check-btn">
                  <a-checkbox v-model:checked="item.isSelected" @change="handleSelected" />
                </div>
                <div class="name">{{ item.sheetName }}</div>
              </div>
            </div>
          </div>
        </template>
        <template v-else-if="title === '查看各单位填报进度'">
          <div class="progress-container">
            <div class="progress-item progress-header">
              <div class="progress-org">单位</div>
              <div class="progress-state">进度</div>
            </div>
            <div class="progress-content">
              <div v-for="item in progressList" :key="item.id" class="progress-item">
                <div class="progress-org">{{ item.departmentName }}</div>
                <div class="progress-state">{{ item.progress }}</div>
              </div>
            </div>
          </div>
        </template>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { onMounted, reactive, ref, watch } from 'vue'
import { projectTemplateConfigurationColumns as columns } from '@/config/columns'
import { message, Modal } from 'ant-design-vue'
import dayjs from 'dayjs'
import { useRoute } from 'vue-router'
import useUserStore from '@/stores/user'
import {
  deleteSheetModelApi,
  downloadSheetModelApi,
  getFillProgressApi,
  getProjectOpenStatusApi,
  getSheetListApi,
  setProjectOpenStatusApi,
  summaryProjectDataAndDownloadApi,
  updateSheetConfigApi,
  uploadSheetModelApi,
  useOldSheetModelApi
} from '@/api/busi'

const route = useRoute()
const userStore = useUserStore()
const formRef = ref()
const dataSource = ref([])
const total = ref(0)
const queryParams = reactive({
  status: 1,
  page: 1,
  pageSize: 20,
  period: dayjs()
})
const form = ref({})
const visible = ref(false)
const uploading = ref(false)
const title = ref('新增')
const openStatus = ref(false)
const picker = ref('month') // 统计年度/月度 month/year
const checkAllTemplate = ref(false)
const listOfPreviousTemplates = ref([]) // 之前的模板
const progressList = ref([]) // 进度情况
const period = ref(dayjs())
const fileList = ref([])
const projectDetail = ref({})

watch(
  () => route.params,
  () => {
    init()
  }
)

const checkSummaryItems = (_rule, value) => {
  if (value === '') {
    return Promise.reject('请输入汇总行/列')
  } else {
    if (form.value.SummaryType === '行') {
      // 行校验
      const objRegExp = /^\d+\+\d\+\d+$/
      if (objRegExp.test(value)) {
        return Promise.resolve()
      } else {
        return Promise.reject('格式必须是"数字+数字+数字"格式')
      }
    } else if (form.value.SummaryType === '列') {
      // 列校验
      const objRegExp = /^([A-Z]\/)+$/
      if (objRegExp.test(value)) {
        let strArr = value.split('/')
        let whetherToIncrementOrNot = true // 是否是连续的
        for (let i = 0; i < strArr.length; i++) {
          if (strArr[i + 1]) {
            let nextChar = String.fromCharCode(strArr[i].charCodeAt(0) + 1) // 获取下一个字符
            if (nextChar !== strArr[i + 1]) {
              whetherToIncrementOrNot = false
              break
            }
          }
        }
        if (whetherToIncrementOrNot) {
          return Promise.resolve()
        } else {
          return Promise.reject('列名必须是连续的字母')
        }
      } else {
        return Promise.reject('格式必须是"字母/"格式')
      }
    } else {
      return Promise.reject('请先选择汇总模式')
    }
  }
}

const getProgressList = () => {
  let { id, periodType } = projectDetail.value
  let params = {
    ProjectId: id,
    PeriodId:
      periodType === '年度'
        ? dayjs(queryParams.period).format('YYYY')
        : dayjs(queryParams.period).format('YYYYMM')
  }
  getFillProgressApi(params).then((res) => {
    progressList.value = res.items.filter(
      (item) => item.departmentName !== '管理员组' && item.departmentName !== '管理员组'
    )
  })
}

// 查询以前某个月的模板
const handleSearchListOfPreviousTemplates = () => {
  let { id, periodType } = projectDetail.value
  let params = {
    ProjectId: id,
    PeriodId:
      periodType === '年度'
        ? dayjs(period.value).format('YYYY')
        : dayjs(period.value).format('YYYYMM')
  }
  getSheetListApi(params).then((res) => {
    listOfPreviousTemplates.value = res.items
  })
}
// 是否全选
const handleSelectedAll = (val) => {
  listOfPreviousTemplates.value.forEach((item) => {
    item.isSelected = val.target.checked
  })
}
const handleSelected = () => {
  // listOfPreviousTemplates.value[index].isSelected = !listOfPreviousTemplates.value[index].isSelected
  checkAllTemplate.value = !listOfPreviousTemplates.value.some((item) => !item.isSelected)
  console.log(checkAllTemplate.value)
}
const disabledDate = (current) => {
  // Can not select days before today and today
  if (picker.value === 'year') {
    return current && current.isAfter(dayjs(dayjs().add(1, 'year').format('YYYY-01-01')))
  } else {
    return current && current.isAfter(dayjs(dayjs().add(1, 'month').format('YYYY-MM-01')))
  }
}
//查看填报进度
const checkTheProgressOfTheReport = () => {
  // 判断必须都配置了
  let isNull = dataSource.value.some((item) => !item.summaryType)
  if (isNull) {
    message.error('请先配置模板')
    openStatus.value = false
    return
  }
  title.value = '查看各单位填报进度'
  visible.value = true
  getProgressList()
}
// 变更发布状态
const handleChangeStatus = (val) => {
  if (!dataSource.value || dataSource.value.length === 0) {
    message.error('请先上传模板')
    openStatus.value = false
    return
  }
  if (val) {
    // 判断必须都配置了才能发布
    let isNull = dataSource.value.some((item) => !item.summaryType)
    if (isNull) {
      message.error('请先配置模板')
      openStatus.value = false
      return
    }
    if (projectDetail.value.id) {
      let { id, periodType } = projectDetail.value
      let params = {
        ProjectId: id,
        PeriodId:
          periodType === '年度'
            ? dayjs(queryParams.period).format('YYYY')
            : dayjs(queryParams.period).format('YYYYMM'),
        Status: val ? '开启填报' : '关闭填报'
      }
      setProjectOpenStatusApi(params).then(() => {})
    }
  } else {
    if (projectDetail.value.id) {
      let { id, periodType } = projectDetail.value
      let params = {
        ProjectId: id,
        PeriodId:
          periodType === '年度'
            ? dayjs(queryParams.period).format('YYYY')
            : dayjs(queryParams.period).format('YYYYMM'),
        Status: val ? '开启填报' : '关闭填报'
      }
      setProjectOpenStatusApi(params).then(() => {})
    }
  }
}

// 导出
const handleExport = () => {
  // 判断必须都配置了
  let isNull = dataSource.value.some((item) => !item.summaryType)
  if (isNull) {
    message.error('请先配置模板')
    openStatus.value = false
    return
  }
  let { id, periodType } = projectDetail.value
  let params = {
    ProjectId: id,
    PeriodId:
      periodType === '年度'
        ? dayjs(queryParams.period).format('YYYY')
        : dayjs(queryParams.period).format('YYYYMM'),
    t: Date.now()
  }
  summaryProjectDataAndDownloadApi(params).then((res) => {
    // 创建一个标签
    let link = document.createElement('a')
    link.href = `${res}`
    // 设置文件下载的名称，（自定义）
    link.download = `汇总数据${params.PeriodId}.xlsx`
    // 模拟点击事件，此时页面将进行下载
    link.click()
  })
}

const getList = () => {
  let { id, periodType } = projectDetail.value
  let params = {
    ProjectId: id,
    PeriodId:
      periodType === '年度'
        ? dayjs(queryParams.period).format('YYYY')
        : dayjs(queryParams.period).format('YYYYMM')
  }
  getSheetListApi(params).then((res) => {
    total.value = res.totleCount
    dataSource.value = res.items
  })
  getOpenStatus()
}
const handleSearch = () => {
  dataSource.value = []
  queryParams.page = 1
  getList()
}
// 复用之前的模板
const handleCopyTemplate = () => {
  visible.value = true
  title.value = '复用以前的模板'
  handleSearchListOfPreviousTemplates()
}
const handleDownloadTemplate = async (row) => {
  let res = await downloadSheetModelApi({ fid: row.id })
  // 创建一个标签
  let link = document.createElement('a')

  // let blob = new Blob([res], {
  //   type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8'
  // })
  // link.href = window.URL.createObjectURL(blob)

  link.href = res
  // 设置文件下载的名称，（自定义）
  link.download = `${
    projectDetail.value.periodType === '年度'
      ? dayjs(queryParams.period).format('YYYY')
      : dayjs(queryParams.period).format('YYYYMM')
  }-${row.sheetName}`
  // 模拟点击事件，此时页面将进行下载
  link.click()
}

const handleOk = () => {
  if (title.value.indexOf('配置') > -1) {
    formRef.value
      .validateFields()
      .then(() => {
        let { id, periodType } = projectDetail.value
        let params = {
          ProjectId: id,
          PeriodId:
            periodType === '年度'
              ? dayjs(queryParams.period).format('YYYY')
              : dayjs(queryParams.period).format('YYYYMM'),
          ...form.value
        }
        // 如果最后一个是/ 就给删除了
        if (params.SummaryItems[params.SummaryItems.length - 1] === '/') {
          params.SummaryItems = params.SummaryItems.substring(0, params.SummaryItems.length - 1)
        }
        updateSheetConfigApi(params).then(() => {
          message.success('操作成功')
          visible.value = false
          getList()
        })
      })
      .catch(() => {})
  } else if (title.value === '复用以前的模板') {
    let isSelectedSome = listOfPreviousTemplates.value.some((item) => item.isSelected)
    if (!isSelectedSome) {
      message.error('请选择模板')
    }
    let { id, periodType } = projectDetail.value
    let params = {
      ProjectId: id,
      PeriodId:
        periodType === '年度'
          ? dayjs(queryParams.period).format('YYYY')
          : dayjs(queryParams.period).format('YYYYMM'),
      OldSheetIds: []
    }
    listOfPreviousTemplates.value.forEach((item) => {
      if (item.isSelected) {
        params.OldSheetIds.push(item.id)
      }
    })
    useOldSheetModelApi(params).then(() => {
      message.success('操作成功')
      getList()
      visible.value = false
    })
  }
}

const handleDel = (row) => {
  if (openStatus.value) {
    message.error('请先关闭发布状态')
    return
  }
  Modal.confirm({
    title: '提示',
    content: '确认删除吗?',
    onOk: () => {
      deleteSheetModelApi({ SheetID: row.id }).then(() => {
        message.success('操作成功')
        getList()
      })
    }
  })
}

const handleDisposition = (row) => {
  visible.value = true
  title.value = `${row.sheetName}配置`
  form.value = {
    id: row.id,
    SheetName: row.sheetName,
    SummaryType: row.summaryType,
    SummaryItems: row.summaryType === '列' ? row.summaryItems + '/' : row.summaryItems,
    Description: row.description
  }
}

const beforeUpload = (file) => {
  const allowFormat =
    file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
    file.type === 'application/vnd.ms-excel' ||
    file.type === 'xlsx'
  if (!allowFormat) {
    message.error('只允许上传excel文件!')
  }
  const fileSize = file.size / 1024 / 1024 < 5
  if (!fileSize) {
    message.error('文件应当小于5MB!')
  }
  // return allowFormat && fileSize
  return fileSize
}

const handleChange = (info) => {
  if (info.file.status === 'done') {
    getList()
    message.success('上传成功')
  }
  if (info.file.status === 'error') {
    message.error('上传失败')
  }
}

const handleUploadTemplate = async (options) => {
  let { file } = options
  const formData = new FormData()
  formData.append('file', file)
  try {
    // 091AE4DD6A664D748A7CFE310C5F91AB
    uploading.value = true

    let { id, periodType } = projectDetail.value
    let params = {
      ProjectId: id,
      PeriodId:
        periodType === '年度'
          ? dayjs(queryParams.period).format('YYYY')
          : dayjs(queryParams.period).format('YYYYMM')
    }
    let uploadRes = await uploadSheetModelApi(formData, params)
    uploading.value = false
    options.onSuccess()
  } catch (e) {
    console.log(e)
  }
}

const getOpenStatus = () => {
  if (projectDetail.value.id) {
    let params = {
      ProjectId: route.params.id
    }
    if (projectDetail.value.periodType === '年度') {
      params.PeriodId = dayjs(queryParams.period).format('YYYY')
    } else {
      params.PeriodId = dayjs(queryParams.period).format('YYYYMM')
    }

    getProjectOpenStatusApi(params).then((res) => {
      openStatus.value = !!(res && res.openStatus === '开启填报')
    })
  }
}

const init = () => {
  // 数据初始化
  picker.value = 'month'
  dataSource.value = []
  total.value = 0
  queryParams.value = {
    status: 1,
    page: 1,
    pageSize: 20,
    period: dayjs()
  }
  form.value = {}
  visible.value = false
  uploading.value = false
  openStatus.value = false
  checkAllTemplate.value = false
  listOfPreviousTemplates.value = []
  progressList.value = []
  period.value = dayjs()
  fileList.value = []
  projectDetail.value = {}

  projectDetail.value = userStore.menuList.find((item) => item.id === route.params.id)
  if (projectDetail.value) {
    if (projectDetail.value.periodType === '年度') {
      picker.value = 'year'
    } else {
      picker.value = 'month'
    }
    handleSearch()
  }
}

onMounted(() => {
  init()
})
</script>

<style lang="less" scoped>
.search-row {
  .status-item {
    margin-right: 30px;
    height: 20px;
    line-height: 20px;
    .label {
    }
    .value {
      font-weight: bold;
      color: #999;
    }
  }
}
.right-btn-container {
  .ant-btn {
    margin-left: 10px;
  }
}
.copy-template-container {
  .copy-template-header {
    height: 50px;
    display: flex;
    align-items: center;
    .check-btn {
      width: 30px;
    }
    .label {
      width: 70px;
    }
    .cycle {
      width: calc(100% - 30px - 70px - 80px);
      .ant-picker {
        width: 100%;
      }
    }
    .search-btn {
      width: 80px;
      display: flex;
      align-items: center;
      justify-content: center;
      .ant-btn {
        width: 80%;
      }
    }
  }
  .previous-template-list-container {
    height: 40vh;
    border: 1px solid #eee;
    border-radius: 5px;
    padding: 10px;
    box-sizing: border-box;
    overflow-y: auto;
    .list-item {
      height: 30px;
      display: flex;
      align-items: center;
      .check-btn {
        margin-right: 10px;
      }
    }
  }
}
.progress-container {
  width: 100%;
  border: 1px solid #ccc;
  border-radius: 5px;
  overflow: hidden;
  .progress-content {
    height: 40vh;
    overflow-y: auto;
  }
  .progress-item {
    height: 40px;
    display: flex;
    align-items: center;
    border-bottom: 1px solid #ccc;
    padding: 0 10px;
    .progress-org {
      height: 40px;
      line-height: 40px;
      width: 80%;
      white-space: nowrap;
      border-right: 1px solid #ccc;
    }
    .progress-state {
      width: 20%;
      text-align: center;
    }
  }
  .progress-header {
    background-color: #f2f2f2;
  }
}
//ant-upload-select
:deep(.ant-upload) {
  width: auto !important;
  height: 20px !important;
  margin: 0 0 0 10px !important;
  border: none !important;
}
</style>
